<template>
  <div class="process-panel__container" :style="{ width: `${this.width}px` }">
    <el-collapse v-model="activeTab">
      <el-collapse-item name="base">
        <div slot="title" class="panel-tab__title">常规</div>
        <element-base-info :id-edit-disabled="idEditDisabled" :business-object="elementBusinessObject" :type="elementType" :model="model" />
      </el-collapse-item>
      <el-collapse-item name="condition">
        <div slot="title" class="panel-tab__title">人员配置</div>
        <div>
          <!--  label-width="68px" -->
          <el-form :model="form" label-width="90px">
            <el-form-item label="规则类型" prop="type">
              <el-select v-model="form.type" clearable style="width: 100%">
                <el-option v-for="dict in dict.type.bpm_task_assign_rule_type" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.type === 10" label="指定角色" prop="roleIds">
              <el-select v-model="form.roleIds" multiple clearable style="width: 100%">
                <el-option v-for="item in roleOptions" :key="parseInt(item.roleId)" :label="item.roleName" :value="parseInt(item.roleId)" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.type === 20 || form.type === 21" label="指定部门" prop="deptIds">
              <treeselect v-model="form.deptIds" :options="deptTreeOptions" multiple flat :defaultExpandLevel="3" placeholder="请选择指定部门" :normalizer="normalizer" />
            </el-form-item>
            <el-form-item v-if="form.type === 22" label="指定岗位" prop="postIds">
              <el-select v-model="form.postIds" multiple clearable style="width: 100%">
                <el-option v-for="item in postOptions" :key="parseInt(item.postId)" :label="item.postName" :value="parseInt(item.postId)" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.type === 30" label="指定用户" prop="userIds">
              <el-select v-model="form.userIds" multiple clearable style="width: 100%">
                <el-option v-for="item in userOptions" :key="parseInt(item.userId)" :label="item.nickName" :value="parseInt(item.userId)" />
              </el-select>
            </el-form-item>

            <el-form-item v-if="form.type === 50" label="指定脚本" prop="scripts">
              <el-select v-model="form.scripts" multiple clearable style="width: 100%">
                <el-option v-for="dict in dict.type.bpm_task_assign_script" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script>
import ElementBaseInfo from './base/ElementBaseInfo'
import ElementOtherConfig from './other/ElementOtherConfig'
import ElementTask from './task/ElementTask'
import ElementMultiInstance from './multi-instance/ElementMultiInstance'
import FlowCondition from './flow-condition/FlowCondition'
import SignalAndMassage from './signal-message/SignalAndMessage'
import ElementListeners from './listeners/ElementListeners'
import ElementProperties from './properties/ElementProperties'
import ElementForm from './form/ElementForm'
import UserTaskListeners from './listeners/UserTaskListeners'

import { getTaskAssignRuleList } from '@/api/bpm/taskAssignRule'
import { listSimpleRoles } from '@/api/power/role'
import { listSimpleDepts } from '@/api/power/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listSimplePosts } from '@/api/power/post'
import { listSimpleUsers } from '@/api/power/user'
/**
 * 侧边栏
 * @Author MiyueFE
 * @Home https://github.com/miyuesc
 * @Date 2021年3月31日18:57:51
 */
export default {
  name: 'MyPropertiesPanelRule',
  dicts: ['bpm_task_assign_script', 'bpm_model_form_type', 'bpm_task_assign_rule_type'],
  components: {
    UserTaskListeners,
    ElementForm,
    ElementProperties,
    ElementListeners,
    SignalAndMassage,
    FlowCondition,
    ElementMultiInstance,
    ElementTask,
    ElementOtherConfig,
    ElementBaseInfo,
    Treeselect
  },
  componentName: 'MyPropertiesPanelRule',
  props: {
    bpmnModeler: Object,
    prefix: {
      type: String,
      default: 'camunda'
    },
    width: {
      type: Number,
      default: 480
    },
    idEditDisabled: {
      type: Boolean,
      default: false
    },
    model: Object // 流程模型的数据
  },
  provide() {
    return {
      prefix: this.prefix,
      width: this.width
    }
  },
  data() {
    return {
      formSub: [],
      activeTab: 'base',
      elementId: '',
      elementType: '',
      elementBusinessObject: {}, // 元素 businessObject 镜像，提供给需要做判断的组件使用
      conditionFormVisible: false, // 流转条件设置
      formVisible: false, // 表单配置
      form: {}, // 表单
      // rules: {
      //   // 表单校验规则
      //   type: [{ required: true, message: '规则类型不能为空', trigger: 'change' }],
      //   roleIds: [{ required: true, message: '指定角色不能为空', trigger: 'change' }],
      //   deptIds: [{ required: true, message: '指定部门不能为空', trigger: 'change' }],
      //   postIds: [{ required: true, message: '指定岗位不能为空', trigger: 'change' }],
      //   userIds: [{ required: true, message: '指定用户不能为空', trigger: 'change' }],
      //   scripts: [{ required: true, message: '指定脚本不能为空', trigger: 'change' }]
      // },

      // 各种下拉框
      roleOptions: [],
      deptOptions: [],
      deptTreeOptions: [],
      postOptions: [],
      userOptions: []
    }
  },
  watch: {
    elementId: {
      handler() {
        this.activeTab = 'base'
      }
    },
    formSub: {
      handler(val) {
        this.$emit('change-form', val)
      },
      deep: true
    }
  },
  created() {
    this.initModels()
  },
  methods: {
    initModels() {
      // 初始化 modeler 以及其他 moddle
      if (!this.bpmnModeler) {
        // 避免加载时 流程图 并未加载完成
        this.timer = setTimeout(() => this.initModels(), 10)
        return
      }
      if (this.timer) clearTimeout(this.timer)
      window.bpmnInstances = {
        modeler: this.bpmnModeler,
        modeling: this.bpmnModeler.get('modeling'),
        moddle: this.bpmnModeler.get('moddle'),
        eventBus: this.bpmnModeler.get('eventBus'),
        bpmnFactory: this.bpmnModeler.get('bpmnFactory'),
        elementFactory: this.bpmnModeler.get('elementFactory'),
        elementRegistry: this.bpmnModeler.get('elementRegistry'),
        replace: this.bpmnModeler.get('replace'),
        selection: this.bpmnModeler.get('selection')
      }
      this.getActiveElement()
      this.formSub = []
      // 获得列表
      this.getList()

      // 获得角色列表
      this.roleOptions = []
      listSimpleRoles().then((response) => {
        this.roleOptions.push(...response.data)
      })
      // 获得部门列表
      this.deptOptions = []
      this.deptTreeOptions = []
      listSimpleDepts().then((response) => {
        this.deptOptions.push(...response.data)
        this.deptTreeOptions.push(...this.handleTree(response.data, 'id'))
      })
      // 获得岗位列表
      this.postOptions = []
      listSimplePosts().then((response) => {
        this.postOptions.push(...response.data)
      })
      // 获得用户列表
      this.userOptions = []
      listSimpleUsers().then((response) => {
        this.userOptions.push(...response.data)
      })
    },
    /** 获得任务分配规则列表 */
    getList() {
      getTaskAssignRuleList({
        modelId: this.model.id,
        processDefinitionId: undefined
      }).then((response) => {
        response.data.forEach((row) => {
          this.form = {}
          this.form = {
            ...row,
            options: [],
            roleIds: [],
            deptIds: [],
            postIds: [],
            userIds: [],
            scripts: []
          }
          // 将 options 赋值到对应的 roleIds 等选项
          if (row.type === 10) {
            this.form.roleIds.push(...row.options)
          } else if (row.type === 20 || row.type === 21) {
            this.form.deptIds.push(...row.options)
          } else if (row.type === 22) {
            this.form.postIds.push(...row.options)
          } else if (row.type === 30) {
            this.form.userIds.push(...row.options)
          } else if (row.type === 50) {
            this.form.scripts.push(...row.options)
          }
          this.formSub.push(JSON.parse(JSON.stringify(this.form)))
        })
      })
    },
    getActiveElement() {
      // 初始第一个选中元素 bpmn:Process
      this.initFormOnChanged(null)
      this.bpmnModeler.on('import.done', (e) => {
        this.initFormOnChanged(null)
      })
      // 监听选择事件，修改当前激活的元素以及表单
      this.bpmnModeler.on('selection.changed', ({ newSelection }) => {
        this.initFormOnChanged(newSelection[0] || null)
      })
      this.bpmnModeler.on('element.changed', ({ element }) => {
        // 保证 修改 "默认流转路径" 类似需要修改多个元素的事件发生的时候，更新表单的元素与原选中元素不一致。
        if (element && element.id === this.elementId) {
          this.initFormOnChanged(element)
        }
      })
    },
    // 初始化数据
    initFormOnChanged(element) {
      let activatedElement = element
      // debugger
      if (!activatedElement) {
        activatedElement = window.bpmnInstances.elementRegistry.find((el) => el.type === 'bpmn:Process') ?? window.bpmnInstances.elementRegistry.find((el) => el.type === 'bpmn:Collaboration')
      }
      if (!activatedElement) return
      console.log(`
              ----------
      select element changed:
                id:  ${activatedElement.id}
              type:  ${activatedElement.businessObject.$type}
              model: ${this.model}
              ----------
              `)

      this.formSub.forEach((row) => {
        if (row.taskDefinitionKey == activatedElement.id) {
          this.form = row
        }
      })

      window.bpmnInstances.bpmnElement = activatedElement
      this.bpmnElement = activatedElement
      this.elementId = activatedElement.id
      this.elementType = activatedElement.type.split(':')[1] || ''
      this.elementBusinessObject = JSON.parse(JSON.stringify(activatedElement.businessObject))

      this.conditionFormVisible = !!(this.elementType === 'SequenceFlow' && activatedElement.source && activatedElement.source.type.indexOf('StartEvent') === -1)
      this.formVisible = this.elementType === 'UserTask' || this.elementType === 'StartEvent'
    },
    beforeDestroy() {
      window.bpmnInstances = null
    },
    // 格式化部门的下拉框
    normalizer(node) {
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    }
  }
}
</script>
